/////precompiled////////
#include "precompiled.h"
////////////////////////


#include "svl_TPostMessage.h"
using namespace svl;
                      
// TPostMessage ///////////////////////////////////////////////////////////////

WPARAM TPostMessage::WParam = 99999;
TPostMessage::TManager TPostMessage::manager;
int TPostMessage::cntObjects = 0;

//
void TPostMessage::WaitAllReceive()
{
  MSG msg; while (cntObjects != 0) 
  { 
    if (0 != ::PeekMessage( &msg, NULL, 0, 0, PM_REMOVE)) 
    {
      //if (msg.message == WM_QUIT)
      //    manager.cntObjects = 0;
      ::TranslateMessage(&msg); 
      ::DispatchMessage (&msg);
    }
  } 

  //while (manager.window->cntObjects) { Application->ProcessMessages();}
}

//
void TPostMessage::Post()
{
  if (isPost) { Except("Post[isPost]");} isPost = true;
  if (!manager.Win) { manager.Win = new TWin;}
  cntObjects++;
  manager.Win->Post(this);
}

//
void TPostMessage::TWin::Post(TPostMessage *Message)
{
  ::PostMessage(TWin::Handle(),WM_COMMAND,WParam,(long)Message);
}

//
LRESULT TPostMessage::TWin::TWindow_WndProc(TWindow::TMessage &Message)
{
  if (Message.Msg == WM_COMMAND && Message.WParam == WParam)
  {
    TPostMessage *M = (TPostMessage*)Message.LParam;
    M->TPostMessage_Receive(); M->cntObjects--; delete M; 
    return 0;
  }
  else { return TWindow::TWindow_WndProc(Message);}
}
